USE NutritionTracker
GO
IF EXISTS (SELECT 1 FROM sysobjects WHERE ID = object_id(N'Session_Get') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
	DROP PROCEDURE Session_Get
GO
CREATE PROC Session_Get
(
@SessionID	UNIQUEIDENTIFIER,
@IPAddress	VARCHAR(11),
@DateTime	SMALLDATETIME,
@MaxTimeSpan	TINYINT
)
AS
BEGIN

SET NOCOUNT ON

DECLARE		@AppUserID	INT,
	@RowCount TINYINT

SELECT		@AppUserID = AppUserID
FROM		Session		WITH(NOLOCK)
WHERE		SessionID = @SessionID

UPDATE		Session
SET		LastActiveTime = GetDate()
WHERE		AppUserID = @AppUserID	
AND		IPAddress = @IPAddress
AND		DATEDIFF(MINUTE,LastActiveTime,@DateTime) <= @MaxTimeSpan

SET @RowCount = @@ROWCOUNT

IF @ROWCOUNT != 1
BEGIN
	DELETE FROM		Session
	WHERE		AppUserID = @AppUserID
END

SELECT		a.AppUserID,
		a.TimeZoneOffset
FROM		AppUser a	WITH(NOLOCK)
INNER JOIN	Session s	WITH(NOLOCK)
	ON		a.AppUserID = s.AppUserID
WHERE		s.SessionID = @SessionID

SET NOCOUNT OFF

END
GO
GRANT EXECUTE ON Session_Get TO NUTRKR_WEB
GO